﻿using Mysoft.QuickCode.NPOI.HSSF.Util;
using Mysoft.QuickCode.NPOI.SS.UserModel;
using Mysoft.QuickCode.Office.Excel.Data;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;

namespace Mysoft.QuickCode.Office.Excel
{
    /// <summary>
    /// 数据集工具
    /// </summary>
    public class DataSetTool
    {
        private List<KeyValuePair<string, List<List<ExcelCell>>>> allExcelCellList = new List<KeyValuePair<string, List<List<ExcelCell>>>>();

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="tableList">数据列表和表格名称</param>
        public DataSetTool(List<KeyValuePair<string, DataTable>> tableList)
        {
            int maxColunm = 0;
            foreach (var kv in tableList)
            {
                //计算出最大列数
                maxColunm = Math.Max(maxColunm, kv.Value.Columns.Count);
            }

            //构建待导出数据
            foreach (var kv in tableList)
            {
                var excelCellList = kv.Value.ToExcelCellList();
                int len = excelCellList.First().Count();

                //插入标题行
                var titleRow = new List<ExcelCell>();
                for (int i = 0; i < len; i++)
                {
                    titleRow.Add(new ExcelCell()
                    {
                        Field = $"_default_title_{i}",
                        Text = kv.Key,
                        Align = "left",
                        BackgroundColor = HSSFColor.Grey25Percent.Index,
                        ColumnGroup = kv.Key
                    });
                }
                excelCellList.Insert(0, titleRow);


                //加到全集列表
                allExcelCellList.Add(new KeyValuePair<string, List<List<ExcelCell>>>(kv.Key, excelCellList));
            }
        }

        /// <summary>
        /// 生成IWorkbook对象，默认为xls格式版本的EXCEL文件
        /// </summary>
        /// <returns></returns>
        public IWorkbook GetWorkbook()
        {
            var excelOut = new List<List<ExcelCell>>();
            IWorkbook workbook = null;
            foreach (var kv in allExcelCellList)
            {
                workbook = ExcelCreator.ExportToExcel(workbook, kv.Value, null, new ExportExcelSetting() { HeaderRowCount = 2, FrozenHeader = false }, createMode: CreateMode.AppendBlock);
            }

            return workbook;
        }

        /// <summary>
        /// 获取所有待导出的数据结构，允许用户在导出前调整其格式或内容
        /// </summary>
        /// <returns></returns>
        public List<KeyValuePair<string, List<List<ExcelCell>>>> GetAllExcelCellList()
        {
            return allExcelCellList;
        }
    }
}
